#include <header.h>

int main()
{
    const char * port = "9090";
    const char * ip = "0.0.0.0";

    int server_fd = socket(AF_INET , SOCK_STREAM , 0);
    ERROR_CHECK(server_fd , -1 , "socket");

    struct sockaddr_in serveraddr;
    memset(&serveraddr , 0 , sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(port));
    serveraddr.sin_addr.s_addr = inet_addr(ip);

    int ret = bind(server_fd , (const struct sockaddr *)&serveraddr , 
         sizeof(serveraddr));
    ERROR_CHECK(ret , -1 , "bind");

    int ret2 = listen(server_fd , 10);
    ERROR_CHECK(ret2 , -1 , "listen");

    int net_fd = accept(server_fd , NULL , NULL);
    ERROR_CHECK(net_fd , -1 , "accept");
    printf("客户端连接成功！\n");

    while(1)
    {
        fd_set set;
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO , &set);
        FD_SET(net_fd , &set);

        select(net_fd + 1 , &set , NULL , NULL , NULL);

        if(FD_ISSET(STDIN_FILENO , &set))
        {
            char buf[1024] = {0};
            int len = read(STDIN_FILENO , buf , sizeof(buf));
            send(net_fd , buf , len , 0);
        }

        if(FD_ISSET(net_fd , &set))
        {
            char buf[1024] = {0};
            int ret = recv(net_fd , buf , sizeof(buf) , 0);

            if(ret == 0)
            {
                printf("对方已断开连接 ！！！ \n");
                break;
            }

            buf[ret] = '\0';
            printf("Client : %s" , buf);
        }
    }

    close(net_fd);
    close(server_fd);

    return 0;
}


